<?php
class database{
    public static function Run(){
        call_user_func("database::".$_SERVER["REQUEST_METHOD"]."_".$_GET["p"]);
    }

    public static function GET_list(){
        if(!file_exists($_GET["s_project_path"]."/data/database.json")){
            echo json_encode([
                "res"=>"OK","list"=>[]
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_GET["s_project_path"]."/data/database.json"),true);
        echo json_encode([
            "res"=>"OK","list"=>$data
        ]);
    }

    public static function POST_add(){
        if(!is_dir($_POST["s_project_path"])){
            // echo $_POST["s_project_path"];
            mkdir($_POST["s_project_path"],0777);
            mkdir($_POST["s_project_path"]."/data",0777);
        }
        if(!file_exists($_POST["s_project_path"]."/data/database.json")){
            file_put_contents($_POST["s_project_path"]."/data/database.json","[]");
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/database.json"),true);
        $rows=[];
        for($i=0;$i<count($_POST["s_col"]);$i++){
            array_push($rows,[
                "s_col"=>$_POST["s_col"][$i],
                "s_cn"=>$_POST["s_cn"][$i],
                "s_regex"=>$_POST["s_regex"][$i],
                "s_attr"=>$_POST["s_attr"][$i],
            ]);
        }
        array_push($data,[
            "id"=>count($data)+1,
            "s_table"=>$_POST["s_table"],
            "i_drop"=>0,
            "rows"=>$rows
        ]);
        
        file_put_contents($_POST["s_project_path"]."/data/database.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_edit(){
        if(!file_exists($_POST["s_project_path"]."/data/database.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/database.json"),true);
        $rows=[];
        for($i=0;$i<count($_POST["s_col"]);$i++){
            array_push($rows,[
                "s_col"=>$_POST["s_col"][$i],
                "s_cn"=>$_POST["s_cn"][$i],
                "s_regex"=>$_POST["s_regex"][$i],
                "s_attr"=>$_POST["s_attr"][$i],
            ]);
        }
        $data[$_POST["id"]-1]["s_table"]=$_POST["s_table"];
        $data[$_POST["id"]-1]["rows"]=$rows;

        file_put_contents($_POST["s_project_path"]."/data/database.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function POST_delete(){
        if(!file_exists($_POST["s_project_path"]."/data/database.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/database.json"),true);
        // print_r($data);
        $data[$_POST["id"]-1]["i_drop"]=1;

        file_put_contents($_POST["s_project_path"]."/data/database.json",json_encode($data,JSON_UNESCAPED_UNICODE));
        echo json_encode([
            "res"=>"OK"
        ],JSON_UNESCAPED_UNICODE);
    }

    public static function GetAttr($attr,$key){
        if(in_array($attr,["INDEX","FULLTEXT"])){
            return "";
        }
        return $attr;
    }

    public static function POST_save(){
        if(!file_exists($_POST["s_project_path"]."/data/database.json")){
            echo json_encode([
                "res"=>"NG","message"=>"无项目更新"
            ]);
            exit;
        }
        $data=json_decode(file_get_contents($_POST["s_project_path"]."/data/database.json"),true);

        $sqls=[];
        $sql_file="";
        foreach ($data as $key => $json) {
            if($json["i_drop"]==1) continue;

            array_push($sqls,"drop table if exists {$json["s_table"]};");
            $sql_file.="drop table if exists {$json["s_table"]};\n";

            $index_sqls=[];
            $sql="create table if not exists {$json["s_table"]} (";
            foreach ($json["rows"] as $count => $row) {
                $sql.="{$row["s_col"]} {$row["s_regex"]} " .self::GetAttr($row["s_attr"],$row["s_col"]).",";
                if(in_array($row["s_attr"],["INDEX","FULLTEXT"])){
                    array_push($index_sqls,"create {$row["s_attr"]} idx_{$row["s_col"]} on {$json["s_table"]}({$row["s_col"]});");
                    $sql_file.="create {$row["s_attr"]} idx_{$row["s_col"]} on {$json["s_table"]}({$row["s_col"]});\n";
                }
            }
            $sql=trim($sql,",");
            $sql.=")charset=utf8mb4;";
            $sql_file.=$sql."\n";
            array_push($sqls,$sql);
            $sqls=array_merge($sqls,$index_sqls);
        }

        // print_r($sqls);exit;
        
        file_put_contents($_POST["s_project_path"]."/data/database.sql",$sql_file);

        try {
            $db=new PDO("mysql:host=".$_POST["s_host"].";dbname=".$_POST["s_dbname"],$_POST["s_user"],$_POST["s_pwd"]);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            foreach ($sqls as $key => $sql) {
                $db->exec($sql);
            }
            echo json_encode(["res"=>"OK"]);
        } catch (PDOException $e) {
            echo json_encode([
                "res"=>"NG",
                "message"=>$e->getMessage()
            ]);
        }
    }
}

database::Run();
?>